import {View, Image, ScrollView, Text} from '@tarojs/components';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import React from 'react';
import {connect} from 'react-redux';
import * as T from './types';
import './index.less';
import {AtIcon} from 'taro-ui';
import actions from './actions';
import {store2Props} from './selectors';
import LandEelements from './components/landElement';
import RightButtons from './components/rightButtons';
import BottomBox from './components/bottomBox';
import AgreeModal from './components/welcome/agreeModal';
import NewcomerModal from './components/welcome/newcomerModal';
import NaviModal from './components/naviModal';
import SettingModal from './components/setting';
import MemberModal from './components/MemberModal/MemberModal';
import DailyExclusiveModal from './components/DailyExclusiveModal/DailyExclusiveModal';
import TaskModal from './components/TaskModal/TaskModal';
import Rank from './components/rank';
import {IPLAND_OSS_HOST} from '../constant';
import {TASK_CONDITION_TYPE, GAME_SHARE_TITLE, OSS_BASE_PATH_PREFIX} from './constant';
import {fetchModal, handleUrl, setModalShow} from 'wmkit';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import MoModal from './components/moModal';
import OuModal from './components/ouModal';

//@ts-ignore
actions().actions.loadReducer();
//@ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class TaroUserCenter extends React.Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      query: {}, // 路径中携带参数
      show: true,
      statusBarHeight: 0,
      navBarHeight: 0,
      windowHeight: 0,
      menuBottonTop: 0,
      menuBottonHeight: 0,
      isModalFlag: false,
      imgUrl: '',
      jumpPage: {},
      nextPopupId: '',
      pics: {
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
      },
    };
  }

  componentDidMount() {
    this.getNavHeight();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillMount(): void {
    this.updateModalStatus('');
  }

  componentDidShow() {
    // 获取路由参数
    this.handleGetRouterParams();
    // 查询用户信息
    this.props.actions.action.loadGameUserInfo();
    // 查询用户信息-判断是否会员
    this.props.actions.action.loadUserInfo();
    // 非会员赠送游戏次数（金币雨）
    this.props.actions.action.giveUserNoVipGameTimes();
    // 获取导航数据
    this.props.actions.action.getNavigationConfig();
    // 获取奖品
    // this.props.actions.action.getLeaderboardRewards();
    // 查询任务
    // this.props.actions.action.getTaskList();
    // 查询游戏任务列表
    this.handleQueryTaskItems({});
    // 判断是否新人
    // this.props.actions.action.loadUserComputedGameTimes();
    // 是否首次进入
    let iplanNotFirstIn = false;
    if (Taro.getStorageSync('iplanNotFirstIn')) iplanNotFirstIn = true;
    this.props.actions.init(iplanNotFirstIn);
    // 获取首页魔欧道具
    this.props.actions.action.propCount();
  }

  getNavHeight() {
    let menuButtonObject = Taro.getMenuButtonBoundingClientRect();
    var sysinfo = Taro.getSystemInfoSync();
    let windowHeight = sysinfo.windowHeight;
    let statusBarHeight = sysinfo.statusBarHeight;
    let menuBottonHeight = menuButtonObject.height;
    let menuBottonTop = menuButtonObject.top;
    let navBarHeight = statusBarHeight + menuBottonHeight + (menuBottonTop - statusBarHeight) * 2;
    this.setState({
      statusBarHeight,
      navBarHeight,
      windowHeight,
      menuBottonTop,
      menuBottonHeight,
    });
  }

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('catching handleGetRouterParams params', params);
    if (params.favorite || params.share) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
    }
    this.setState({
      ...this.state,
      query: params,
    });
  };

  async updateModalStatus(id) {
    const res = await fetchModal('iplandHome');
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, 'iplandHome', popupId);
    this.setState(
      {
        isModalFlag: flagParams.showFlag,
        imgUrl: flagParams.imgUrl,
        jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
        nextPopupId: flagParams.nextPopupId,
      },
      () => {
        if (this.state.nextPopupId && !this.state.isModalFlag) {
          this.isGo(this.state.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.updateModalStatus(id);
  }
  handleClose() {
    this.setState({isModalFlag: false}, async () => {
      if (this.state.nextPopupId) {
        await this.updateModalStatus(this.state.nextPopupId);
      }
    });
  }

  agreeClikc() {
    let {
      actions: {action},
    } = this.props;
    action.commonChange('main.showAgree', false);
    action.commonChange('main.showNewcomer', true);
    Taro.setStorageSync('iplanNotFirstIn', true);
  }

  notAgreeClikc() {
    let {
      actions: {action},
    } = this.props;
    action.commonChange('main.showAgree', false);
    Taro.navigateBack();
  }

  gotoNavi(onlyShowCoinRain) {
    let {
      actions: {action},
    } = this.props;
    action.commonChange('main.showNewcomer', false);
    action.commonChange('main.showNaviModal', true);
    action.commonChange('main.onlyShowCoinRain', onlyShowCoinRain);
  }

  render() {
    let {navBarHeight, statusBarHeight, menuBottonTop, menuBottonHeight} = this.state;
    let {
      main: {
        money,
        showAgree,
        showNewcomer,
        showNaviModal,
        showSettingModal,
        showMemberLoginDailyModal,
        showTaskModal,
        showRankModal,
        dailyGetCoin,
        bottomClickNavigation,
        showOpenMemberModal,
        showMoModal,
        showOuModal,
      },
      actions: {action},
    } = this.props;
    return (
      <View className="container">
        <View className="homeStatusBar" style={{height: statusBarHeight}}></View>
        <ScrollView className="landHome" scrollY>
          <View className="top" style={{height: menuBottonHeight + (menuBottonTop - statusBarHeight) * 2}}>
            <View className="leftBack">
              <AtIcon
                onClick={() => {
                  Taro.navigateBack();
                }}
                customStyle={{zIndex: 2}}
                value="chevron-left"
                size="30"
                color="#000"
              ></AtIcon>
            </View>
            <View
              className="myCoin"
              onClick={(e) => {
                e.stopPropagation();
                Taro.navigateTo({
                  url: '/pages/package-I/syntheticRecharge/index',
                });
              }}
            >
              <Image className="coinImg" src={`${IPLAND_OSS_HOST}home/coin.png`} />
              <Text className="number">{money}</Text>
              <Text className="add">+</Text>
            </View>
          </View>
          <LandEelements />
          {/* 魔-欧 */}
          <RightButtons />
          <BottomBox />
          {/* 首次进入 同意 不同意 */}
          <AgreeModal isOpened={showAgree} onSure={() => this.agreeClikc()} onCancel={() => this.notAgreeClikc()} />
          {/* 新人导航 */}
          <NewcomerModal
            isOpened={showNewcomer}
            vipGoNavi={() => this.gotoNavi(false)}
            notVipGoJingbiyu={() => this.gotoNavi(true)}
          />
          {/* 乐园导航 */}
          <NaviModal
            isOpened={showNaviModal}
            onCancel={() => {
              action.commonChange('main.showNaviModal', false);
              // 导航结束后，显示会员每日登录领取弹窗
              if (dailyGetCoin && !bottomClickNavigation) {
                setTimeout(() => {
                  action.commonChange('main.showMemberLoginDailyModal', true);
                }, 300);
              }
            }}
          />
          {/* 设置 */}
          <SettingModal
            isOpened={showSettingModal}
            onCancel={() => action.commonChange('main.showSettingModal', false)}
          />
          {/* 会员每日登录 */}
          <DailyExclusiveModal
            visible={showMemberLoginDailyModal}
            onCancel={this.handleCancelGameTimesDaily}
            onReceive={this.handleReceive}
          />
          {/* 任务 */}
          <TaskModal
            visible={showTaskModal}
            onCancel={() => {
              action.commonChange('main.showTaskModal', false);
            }}
            onQueryTask={this.handleQueryTaskItems}
          />
          {/* 开通会员 */}
          <MemberModal
            visible={showOpenMemberModal}
            onCancel={() => {
              action.commonChange('main.showOpenMemberModal', false);
            }}
            onActivate={() => this.handleActivateMember()}
          />
          {/* 月度排行 */}
          <Rank isOpened={showRankModal} onCancel={() => action.commonChange('main.showRankModal', false)} />
        </ScrollView>
        <AdvModal
          imgUrl={this.state.imgUrl}
          handleUrl={() => handleUrl(this.state.jumpPage)}
          handleClose={() => this.handleClose()}
          isModalFlag={this.state.isModalFlag}
        />
        <MoModal isOpened={showMoModal} onCancel={() => action.commonChange('main.showMoModal', false)} />
        <OuModal isOpened={showOuModal} onCancel={() => action.commonChange('main.showOuModal', false)} />
      </View>
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.props.actions.action.commonChange('main.showOpenMemberModal', false);
    // 跳转到开通会员界面
    Taro.navigateTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 查询游戏任务列表
   */
  handleQueryTaskItems = (pagation) => {
    // 编辑参数
    const {
      main: {
        task: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadTaskItems(params);
  };

  /**
   * 点击开心收下
   */
  handleReceive = () => {
    console.log('index.tsx handleReceive');
    this.props.actions.action.commonChange('main.showMemberLoginDailyModal', false);
    this.handleQueryGameTimesDaily(false); // 获取游戏次数
  };

  /**
   * 取消
   */
  handleCancelGameTimesDaily = () => {
    this.props.actions.action.commonChange('main.showMemberLoginDailyModal', false);
    this.handleQueryGameTimesDaily(true); // 获取游戏次数
  };

  /**
   * 查询每日领取次数
   */
  handleQueryGameTimesDaily = (type) => {
    console.log('index.tsx handleQueryGameTimesDaily type', type);
    this.props.actions.action.dailyLoginGetCoin(type);
  };

  /**
   * 分享好友
   * @param res
   * @returns
   */
  onShareAppMessage(res) {
    const {
      pics: {gameShareThum},
      query,
    } = this.state;
    if (query && query.taskConditionsType == TASK_CONDITION_TYPE['share']) {
      this.props.actions.action.computedTask({
        id: query.taskId,
      });
    }

    return {
      title: GAME_SHARE_TITLE,
      path: '/pages/package-I/home/index',
      imageUrl: gameShareThum,
      query: 'share=true',
    };
  }

  /**
   * 分享到朋友圈
   * @param res
   * @returns
   */
  onShareTimeline(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      path: '/pages/package-I/home/index',
      query: 'share=true',
    };
  }
}

//create by moon https://github.com/creasy2010/moon
